package com.bawei.mvvm

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.mvvm.databinding.ActivityLoginBinding
import com.bawei.mvvm.http.ApiService
import com.bawei.mvvm.viewmodel.LoginViewModel
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.RequestBody
import javax.inject.Inject

@AndroidEntryPoint
class LoginActivity : AppCompatActivity() {
    private lateinit var activityLoginBinding: ActivityLoginBinding
    private val loginViewModel: LoginViewModel by viewModels()//获得viewModel  惰性初始化委托给viewModels(）

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityLoginBinding =  ActivityLoginBinding.inflate(layoutInflater)
        setContentView( activityLoginBinding.root)




        activityLoginBinding.btLogin.setOnClickListener {
            var username = activityLoginBinding.etUsername.text.toString()
            var password = activityLoginBinding.etPassword.text.toString()

            //对密码进行加密传给后台服务器：





            var  map = mutableMapOf<String,String>()
            map.put("username",username)
            map.put("password",password)
            //扩展函数：扩展MutableMap方法--》RequestBody

//            var  str = Gson().toJson(map)
//            var requestBody =RequestBody.create(MediaType.parse("application/json;charset=utf-8"),str)

            loginViewModel.login(map.toBody()).observe(this, Observer {
                if(it.code == 200){
                    Toast.makeText(this,"登陆成功",Toast.LENGTH_LONG).show()
                    ARouter.getInstance().build("/app/main").navigation()
                }else{
                    Toast.makeText(this,"登陆失败"+it.message,Toast.LENGTH_LONG).show()
                }
            })

        }


    }
}